import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import joblib
import sqlite3
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

plt.rcParams["font.sans-serif"] = ["SimHei"]

data = pd.read_csv("dataset.csv")
X = data[["居室数", "厅堂数", "卫生间数", "总面积", "建造年份", "居民楼总层数", "小区户数", "小区绿化率", "物业费用",]]
# print(X)
y = data["价格"]

# 模型加载
estimator1 = joblib.load("linear_regression.pkl")
estimator2 = joblib.load("random_forest.pkl")

st.title("🏠 智能房屋价格预测系统")

with st.sidebar:
    result = st.selectbox("选择模型", ["随机森林", "线性回归"])
    if result == "线性回归":
        model = estimator1
    else:
        model = estimator2

tb1, tb2, tb3 = st.tabs(["房价分布", "特征重要性", "房价预测"])
with tb1:
    st.subheader("房价分布")
    fig, ax = plt.subplots()
    bins = np.linspace(0, 2000, 100)
    ax.hist(y, bins=bins, color="skyblue", edgecolor="black")
    ax.set_title("房价分布（部分数据）")
    ax.set_xlabel("价格(k)")
    ax.set_ylabel("频数")
    st.pyplot(fig)

    fig1 = px.histogram(y, x="价格", nbins=100)
    st.plotly_chart(fig1, use_container_width=True)
with tb2:
    st.subheader("特征重要性")
    # 根据模型类型计算特征重要性
    if result == "线性回归":
        # 线性回归使用系数的绝对值作为特征重要性
        feature_importance = pd.DataFrame({
            "特征": X.columns,
            "重要性": np.abs(model.coef_)
        })
    else:
        # 随机森林直接使用feature_importances_
        feature_importance = pd.DataFrame({
            "特征": X.columns,
            "重要性": model.feature_importances_
        })

    fig = px.bar(feature_importance, x="特征", y="重要性")
    st.plotly_chart(fig, use_container_width=True)
    st.dataframe(feature_importance)
with tb3:
    st.subheader("房价预测")
    bedrooms = st.slider("居室数", min_value=0, max_value=10, value=3)
    living_rooms = st.slider("厅堂数", min_value=0, max_value=5, value=2)
    bathrooms = st.slider("卫生间数", min_value=0, max_value=5, value=1)
    total_area = st.slider("总面积", min_value=10, max_value=400, value=120)
    build_year = st.slider("建造年份", min_value=1940, max_value=2023, value=2023)
    total_floors = st.slider("总楼层数", min_value=1, max_value=40, value=5)
    house_num = st.slider("小区户数", min_value=1, max_value=6000, value=100)
    green = st.slider("小区绿化率(%)", min_value=0, max_value=100, value=30)
    manage_fee = st.slider("物业费用", min_value=0.0, max_value=10.0, value=0.5, step=0.1)
    if st.button("开始预测"):
        X_test = np.array([[bedrooms, living_rooms, bathrooms, total_area, build_year, total_floors, house_num, green, manage_fee]])
        price = model.predict(X_test)[0]
        st.success(f"预测价格：{price:.2f}k")
